package org.linlinjava.litemall.admin.schedule;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.BeanUtil;
import org.linlinjava.litemall.core.util.RedisKey;
import org.linlinjava.litemall.core.util.RedisUtils;
import org.linlinjava.litemall.db.domain.LitemallActivity;
import org.linlinjava.litemall.db.domain.LitemallStatistics;
import org.linlinjava.litemall.db.service.LitemallActivityService;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling
public class ActivityStatisticsScheduleTask {

    private final Log logger = LogFactory.getLog(ActivityStatisticsScheduleTask.class);

    //@Scheduled(cron = "0/30 * * * * ?")
    //或直接指定时间间隔，例如：5秒
    //@Scheduled(fixedRate=5000)
    private void configureTasks() {
        logger.info("---StatisticsScheduleTask start---");

        LitemallActivityService activityService = BeanUtil.getBean(LitemallActivityService.class);

        List<LitemallActivity> activityList = activityService.queryByState(LitemallActivity.StateEnum.shallStatistics());

        List<LitemallStatistics> list = Lists.newArrayList();

        for (LitemallActivity activity : activityList) {
            // 浏览数 报名数 分享数 成团数
            for (LitemallStatistics.BTypeEnum bTypeEnum : LitemallStatistics.BTypeEnum.values()) {
                LitemallStatistics litemallStatistics = new LitemallStatistics();
                litemallStatistics.setRelType(LitemallActivity.TypeEnum.GROUPON.getCode());
                litemallStatistics.setRelId(activity.getId());
                litemallStatistics.setbType(bTypeEnum.getCode());
                String redisCount = RedisUtils.get(RedisKey.getActivityKey(String.valueOf(activity.getId()), String.valueOf(bTypeEnum.getCode())));
                litemallStatistics.setCount(StringUtils.isNotBlank(redisCount) ? Long.valueOf(redisCount) : 0L);
                litemallStatistics.setDeleted(LitemallStatistics.NOT_DELETED);
                list.add(litemallStatistics);
            }
        }
        if (!CollectionUtils.isEmpty(list)) {
            activityService.batchSaveOrUpdateStatistics(list);
        }
        logger.info("---StatisticsScheduleTask end---");
    }
}
